
#include  "head.h"
#include <sqlite3.h>

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        printf("Usage %s server ip  port",argv[0]);
        return -1;
    }


    int sockfd  = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        perror("socket error");
        return -1;
    }
    printf("sockfd = %d \n",sockfd);


    struct sockaddr_in  localaddr;
    socklen_t   len  =  sizeof(struct sockaddr_in);   
    localaddr.sin_family            = AF_INET;
    localaddr.sin_port              = htons(atoi(argv[2]));
    localaddr.sin_addr.s_addr       = inet_addr(argv[1]);



    int on =1 ;
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
   /* int ret = bind(sockfd, (struct sockaddr*)&localaddr,len);
    if(ret < 0)
    {
        perror("bind error");
        return -1;
    }*/
    //printf("bind ok \n");

    int sos = 0;
    int count = 0;
    while(1)
    {
        if(sos == 0)
        {
            printf("等待接入服务器\n");
            sos ++;
        }
        int connfd = connect(sockfd,(struct sockaddr*)&localaddr,len);
        if(connfd < 0)
        {
            sleep(1);
        }
        else break;
    }
    system("clear");
    printf("成功连接在线词典服务器,输入(\033[35m[]\033[0m])退出\n");
    while(1)
    {
        char buf[32] = {0};
        char buff[512] = {0};
        printf("请输入你要查询的单词:");
        scanf("%s",buf);
        int ret = send(sockfd,buf,sizeof(buf),0);
        if(ret < 0)
        {
            perror("send");
            return -1;
        }
        if(!strcmp(buf,"[]"))   break;
        ret = recv(sockfd,buff,sizeof(buff),0);
        if(ret < 0)
        {
            perror("recv");
            return -1;
        }
        printf("\033[33m%s\033[0m: \033[32m%s\033[0m\n",buf,buff);
    }
    close(sockfd);
    return 0;
}
